package com.psycho.sys.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.psycho.sys.api.entity.Appointment;
import com.psycho.sys.api.entity.Counselor;
import com.psycho.sys.api.entity.ConsultationRecord;
import com.psycho.sys.api.mapper.AppointmentMapper;
import com.psycho.sys.api.mapper.CounselorMapper;
import com.psycho.sys.api.mapper.ConsultationRecordMapper;
import com.psycho.sys.api.service.StudentConsultationService;
import com.psycho.sys.api.vo.AppointmentVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 学生心理咨询服务实现类
 */
@Service
public class StudentConsultationServiceImpl implements StudentConsultationService {

    @Autowired
    private CounselorMapper counselorMapper;

    @Autowired
    private AppointmentMapper appointmentMapper;

    @Autowired
    private ConsultationRecordMapper consultationRecordMapper;

    @Override
    public List<Counselor> listCounselors(String specialization, Double minRating) {
        LambdaQueryWrapper<Counselor> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(specialization != null, Counselor::getSpecialization, specialization)
                .ge(minRating != null, Counselor::getRating, minRating)
                .eq(Counselor::getStatus, 1)
                .orderByDesc(Counselor::getRating);
        return counselorMapper.selectList(wrapper);
    }

    @Override
    @Transactional
    public boolean createAppointment(Appointment appointment) {
        appointment.setStatus(0); // 设置状态为待确认
        appointment.setCreateTime(LocalDateTime.now());
        appointment.setUpdateTime(LocalDateTime.now());
        return appointmentMapper.insert(appointment) > 0;
    }

    @Override
    public List<Appointment> listMyAppointments(Long userId, Integer status) {
        LambdaQueryWrapper<Appointment> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Appointment::getUserId, userId)
                .eq(status != null, Appointment::getStatus, status)
                .orderByDesc(Appointment::getCreateTime);
        return appointmentMapper.selectList(wrapper);
    }

    @Override
    @Transactional
    public boolean cancelAppointment(Long appointmentId, String reason) {
        Appointment appointment = appointmentMapper.selectById(appointmentId);
        if (appointment == null || appointment.getStatus() != 0) {
            return false;
        }
        appointment.setStatus(3); // 设置状态为已取消
        appointment.setCancelReason(reason);
        appointment.setUpdateTime(LocalDateTime.now());
        return appointmentMapper.updateById(appointment) > 0;
    }

    @Override
    public List<ConsultationRecord> listMyConsultationRecords(Long userId) {
        LambdaQueryWrapper<ConsultationRecord> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ConsultationRecord::getUserId, userId)
                .orderByDesc(ConsultationRecord::getCreateTime);
        return consultationRecordMapper.selectList(wrapper);
    }

    @Override
    public ConsultationRecord getConsultationRecord(Long recordId) {
        return consultationRecordMapper.selectById(recordId);
    }

    @Override
    @Transactional
    public boolean submitFeedback(Long recordId, Integer rating, String feedback) {
        ConsultationRecord record = consultationRecordMapper.selectById(recordId);
        if (record == null || record.getStatus() != 1) {
            return false;
        }
        record.setUserRating(rating);
        record.setUserFeedback(feedback);
        record.setUpdateTime(LocalDateTime.now());

        // 更新咨询师评分
        updateCounselorRating(record.getCounselorId(), rating);

        return consultationRecordMapper.updateById(record) > 0;
    }

    /**
     * 更新咨询师评分
     */
    private void updateCounselorRating(Long counselorId, Integer newRating) {
        Counselor counselor = counselorMapper.selectById(counselorId);
        if (counselor != null) {
            // 计算新的平均评分
            double currentRating = counselor.getRating() != null ? counselor.getRating() : 0;
            int currentCount = counselor.getRatingCount() != null ? counselor.getRatingCount() : 0;
            double newAverageRating = (currentRating * currentCount + newRating) / (currentCount + 1);

            counselor.setRating(newAverageRating);
            counselor.setRatingCount(currentCount + 1);
            counselor.setUpdateTime(LocalDateTime.now());
            counselorMapper.updateById(counselor);
        }
    }

    @Override
    public Page<AppointmentVO> pageAppointments(Integer current, Integer size, Long userId, Long counselorId,
            Integer status) {
        Page<AppointmentVO> page = new Page<>(current, size);
        return appointmentMapper.selectAppointmentWithDetails(page, userId, counselorId, status);
    }
}